/**
 * Created by Administrator on 2017/3/21.
 */
import React, {Component} from 'react';
import { Form, Input, Radio, Select, InputNumber, Button, Tooltip, message  } from 'antd';
import request from '@/utils/request';
import { connect } from 'dva';
import styles from '../../layouts/password.less';
const FormItem = Form.Item;
const { TextArea } = Input;
let uuid = 2;
const RadioGroup = Radio.Group;
const Option = Select.Option;
class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      meterArr: [1, 2],
      meterActiveKey: ['1', '2'],
      meter1: [],
      meter2: [],
      all_roles:[],
      level:0,
      mode:''
    };
  }
  componentDidMount() {
    const that=this;
    const control_valve=this.props.hardware_configs.control_valve;
    const config_index=this.props.config_index;
    this.setState({
      mode:(control_valve&&control_valve[config_index].enable==1)?control_valve[config_index].mode:""
    })
    if(control_valve&&control_valve[config_index].enable==1&&control_valve[config_index].time_sharing&&control_valve[config_index].time_sharing.length>0){

      uuid=control_valve[config_index].time_sharing.length
      this.setState({
        meterArr:control_valve[config_index].time_sharing.map((item,index)=>{
          return index+1
        }),
        meterActiveKey:control_valve[config_index].time_sharing.map((item,index)=>{
          return (index+1).toString()
        }),
      })
      for(let i=0;i<control_valve[config_index].time_sharing.length;i++){
        this.setState({
          [`meter${i+1}`]:[]
        },function() {
          that.props.form.setFieldsValue({
            [`time-${i+1}`]:control_valve[config_index].time_sharing[i].time,
            [`pressure-${i+1}`]:control_valve[config_index].time_sharing[i].pressure,
          })
        })
      }

    }
  }
  addMeter = () => {
    uuid++;
    this.state.meterArr.push(uuid);
    this.state.meterActiveKey.push(uuid.toString());
    this.setState({
      [`meter${uuid}`]: [],
      meterArr: this.state.meterArr,
      meterActiveKey: this.state.meterActiveKey,
    });
  };
  deleteMeter = (item) => {
    console.log('删除的item', item);
    if (this.state.meterArr.length === 2) {
      console.log('只有一个水表');
      message.error('分时至少需要2个时间')
      return false
    }
    const index = this.state.meterArr.indexOf(item);
    console.log('index', index);
    this.state.meterArr.splice(index, 1);
    this.setState({
      meterArr: this.state.meterArr,
    });
  };
  render() {
    const formItemLayoutWithLabel = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 15},
      }
    };

    const {getFieldDecorator} = this.props.form;
    const control_valve=this.props.hardware_configs.control_valve;
    const config_index=this.props.config_index;
    const meterForms = this.state.meterArr.map((item, index) => {
      return (
        <Form style={{ display: 'flex' }} className={'custom-table-form'} key={index} layout="inline">
          <FormItem
            style={{ flex: '1', marginRight: '0' }}
          >
            {getFieldDecorator(`time-${item}`, {
              initialValue: '',
            })(
              <InputNumber placeholder={'0-23时'} min={0} max={23} style={{  fontWeight: 'bold' ,width:'100%'}}/>,
            )}
          </FormItem>
          <FormItem
            style={{ flex: '1', marginRight: '0' }}

          >
            {getFieldDecorator(`pressure-${item}`, {
              initialValue: '',
            })(
              <InputNumber style={{  fontWeight: 'bold',width:'100%' }}/>,
            )}
          </FormItem>
          <div style={{ width: '80px', lineHeight: '29px', textAlign: 'center', border: '1px solid #d9d9d9' }}>
            <Button
              style={{ height: '22px' }}
              type="danger"
              size="small"
              icon="delete"
              onClick={(e) => {
                e.stopPropagation();
                this.deleteMeter(item);
              }
              }
            >删除
            </Button>
          </div>


        </Form>
      );
    });

    return (
      <div>
        <Form onSubmit={this.handleSubmit}>
          <FormItem
            {...formItemLayoutWithLabel}
            label={(
              <span>
                数据上传间隔(分钟)
            </span>
            )}
          >
            {getFieldDecorator('upload_interval', {
              initialValue: (control_valve&&control_valve[config_index].enable==1)?control_valve[config_index].upload_interval:""
            })(
              <InputNumber style={{width:'100%'}}/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayoutWithLabel}
            label={(
              <span>
                上限压力(KPa)
            </span>
            )}
          >
            {getFieldDecorator('high_error_pressure', {
              initialValue: (control_valve&&control_valve[config_index].enable==1)?control_valve[config_index].high_error_pressure:""
            })(
              <InputNumber style={{width:'100%'}}/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayoutWithLabel}
            label={(
              <span>
                下限压力(KPa)
            </span>
            )}
          >
            {getFieldDecorator('low_error_pressure', {
              initialValue: (control_valve&&control_valve[config_index].enable==1)?control_valve[config_index].low_error_pressure:""
            })(
              <InputNumber style={{width:'100%'}}/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayoutWithLabel}
            label={(
              <span>
              模式
            </span>
            )}>
            {getFieldDecorator('mode', {
              initialValue: this.state.mode,
              rules: [{ required: true, message: '请选择模式' }],
            })(
              <Select  onChange={(e)=>{
                this.setState({
                  mode:e
                })
              }}>
                { [{name:'手动',id:'manual'},{name:'分时',id:'time_sharing'}].map((item, key) => {
                  return (
                    <Option  key={item.id}  value={item.id.toString()}>{item.name}</Option>
                  )
                }) }
              </Select>
            )}
          </FormItem>
          {
            this.state.mode==='manual'&&
            <FormItem
              {...formItemLayoutWithLabel}
              label={(
                <span>
                目标压力(KPa)
            </span>
              )}
            >
              {getFieldDecorator('target_pressure', {
                initialValue:(control_valve&&control_valve[config_index].enable==1)?control_valve[config_index].target_pressure:""
              })(
                <InputNumber min={250} max={320} style={{width:'100%'}}/>
              )}
            </FormItem>
          }
          {
            this.state.mode==='time_sharing'&&
            <FormItem
              {...formItemLayoutWithLabel}
              label={(
                <span>
                分时调压
            </span>
              )}
            >
              <div style={{ border: '1px solid #d9d9d9', marginTop: '10px' }}>

                <div style={{
                  display: 'flex',
                  fontWeight: 'bold',
                  lineHeight: '32px',
                  height: '32px',
                  background: 'rgb(249,249,249)',
                }}>
                  <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>时间</div>
                  <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9', }}>压力</div>
                  <div style={{ width: '80px', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>操作</div>
                </div>
                {meterForms}
                <Button type={'primary'} className={'btn-cyan'} icon={'plus'} block onClick={this.addMeter}>添加时间</Button>

              </div>
            </FormItem>
          }


        </Form>
      </div>
    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);


